package com.mediacloud.app.newsmodule.activity.military_encyclopedia;

import static com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig.getAppServerConfigInfo;

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.jaeger.library.StatusBarUtil;
import com.mediacloud.app.assembly.clickutils.NoDoubleClickUtils;
import com.mediacloud.app.assembly.photoview.PhotoViewAttacher.OnViewTapListener;
import com.mediacloud.app.assembly.util.FileFormatUtils;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.activity.BaseBackActivity;
import com.mediacloud.app.model.interfaces.IPermissionsAgree;
import com.mediacloud.app.model.interfaces.PermissionUtil;
import com.mediacloud.app.model.news.GroupPhotoDataReciver.PhotoItem;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.view.HackyViewPager;
import com.mediacloud.app.newsmodule.view.PictureViewX;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig.ServerAppConfigInfo.NavigateBarStyle;
import com.model.PhotoInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


public class WikiPhotoDetailActivity extends BaseBackActivity {
    private ImageView downloadIco;
    private TextView downloadNumb;
    private ViewPager mViewPager;
    private ArrayList<PhotoInfo> mPhotoUrls = new ArrayList<PhotoInfo>();
    protected List<PhotoItem> photos;

    protected FrameLayout photoContent;
    HashMap<Integer,PictureViewX> pictureViewXHashMap=new HashMap<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setDarkMode(this);

        initView();
        ArrayList<String> photos = getIntent().getStringArrayListExtra("photos");
        int index = getIntent().getIntExtra("index", 0);
        boolean showDownload = getIntent().getBooleanExtra("showDownload", true);
        if (showDownload){
            downloadIco.setVisibility(View.VISIBLE);
        }else {
            downloadIco.setVisibility(View.GONE);
        }
        setImages(photos);
        mViewPager.setCurrentItem(index);
        setTitle("");
        mTitileBar.setBackgroundColor(Color.TRANSPARENT);
        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) mTitileBar.getLayoutParams();
        lp.topMargin = StatusBarUtil.getStatusBarHeight(this);
        mTitileBar.setLayoutParams(lp);
    }


    @Override
    protected String getContent_show_top_color() {
        return "#FFFFFF";
    }



    @Override
    public int getStatusBarColor() {
        return  Color.TRANSPARENT;
    }

    @Override
    protected boolean getFitSystemWindow() {
        return  false;
    }

    @Override
    protected boolean needLoadTopSecondBgSkin() {
        return super.subClassgetNeedTopSecondBgSkin();
    }
    @Override
    protected NavigateBarStyle getNewsDetailNavigateBarStyle() {
        return getAppServerConfigInfo(this).getPhotoNewsBar();
    }


    protected void initView() {
        mTitileBar = findViewById(R.id.rlTitleBar);
        photoContent = findViewById(R.id.photoContent);
        mViewPager = new HackyViewPager(this);
        photoContent.addView(mViewPager, new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        mRootView.setBackgroundColor(Color.BLACK);
        intDownLoadView();


        findViewById(R.id.mTop_back).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
 }


    /**
     * 图片下载相关
     */
    protected void intDownLoadView() {

        downloadNumb = findViewById(R.id.downloadNumb);

        downloadIco = findViewById(R.id.downloadIco);
        downloadIco.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (NoDoubleClickUtils.isDoubleClick()) {
                    return;
                }
                PermissionUtil.INSTANCE.invokeStoragePermission(WikiPhotoDetailActivity.this, new IPermissionsAgree() {
                    @Override
                    public void onAgree() {
                        new SaveImage().execute(mPhotoUrls.get(mViewPager.getCurrentItem()).logo);
                    }

                    @Override
                    public void onRefuse() {

                    }

                    @Override
                    public void hasPermissions() {
                        new SaveImage().execute(mPhotoUrls.get(mViewPager.getCurrentItem()).logo);
                    }
                });


            }
        });
    }


    protected void setImages(List<String> pics) {
        try {
            photos = new ArrayList<PhotoItem>();
            for (int i = 0; i < pics.size(); i++) {
                PhotoItem photoItem = new PhotoItem();
                photoItem.setImage(pics.get(i));
                photoItem.setThumb(pics.get(i));
                photoItem.setNote("");
                photos.add(photoItem);
                mPhotoUrls.add(new PhotoInfo(pics.get(i)));
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (mPhotoUrls.size() == 0) {
                mPhotoUrls.add(new PhotoInfo());
            }
        }
        mViewPager.setAdapter(new SamplePagerAdapter(mPhotoUrls));
        mViewPager.setOffscreenPageLimit(mPhotoUrls.size());
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }



    private class SamplePagerAdapter extends PagerAdapter {
        private ArrayList<PhotoInfo> urls;
        private int urlsSize;
        private int mPosition = 0;
        boolean hideNote = false;

        public SamplePagerAdapter(ArrayList<PhotoInfo> urls) {
            this.urls = urls;
            urlsSize = urls.size();
        }

        @Override
        public int getCount() {
            return urlsSize;
        }

        @Override
        public View instantiateItem(ViewGroup container, int position) {
            if (position >= urlsSize) {
                return null;
            }
            PictureViewX pictureViewX = new PictureViewX(container.getContext());
            pictureViewX.setId(View.generateViewId());
            pictureViewX.mAttacher.setOnViewTapListener(new OnViewTapListener() {
                @Override
                public void onViewTap(View view, float x, float y) {

                }
            });
            pictureViewX.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            if (urls.get(position).isLocalOriginLogo){
                pictureViewX.setImageURL(urls.get(position).logo);
            }else {
                pictureViewX.setThumbnailImageURL(urls.get(position).logo);
            }
            container.addView(pictureViewX, 0);
            pictureViewXHashMap.put(position,pictureViewX);
            return pictureViewX;
        }

        @Override
        public void setPrimaryItem(View container, int position, Object object) {
            if (photos.size() == 0)
                return;
            SpannableString spannableString = new SpannableString((position + 1) + "/" + urlsSize) /*+ "  "+articleItem.getTitle())*/;

            ForegroundColorSpan focusTextColor = new ForegroundColorSpan(Color.parseColor("#D43D3D"));
            spannableString.setSpan(focusTextColor, 0, position >= 9 ? 2 : 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

            downloadNumb.setText(spannableString);
            mPosition = position;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

    }

    @Override
    protected void onDestroy() {

        if (pictureViewXHashMap!=null) {
            pictureViewXHashMap.clear();
        }

        if (photos != null)
            photos.clear();
        super.onDestroy();
    }



    @Override
    public int getLayoutResID() {
        return R.layout.activity_wiki_photo_detail;
    }


    /***
     * 功能：用线程保存图片
     *
     * @author wangyp
     */
    private class SaveImage extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            if (isFinishing() || isDestroyed()) {
                return null;
            }
            String result = "";
            InputStream inputStream = null;
            HttpURLConnection conn = null;
            FileOutputStream outStream = null;
            try {
                String sdcard = Environment.getExternalStorageDirectory().toString();
                File file = new File(sdcard + "/Download");
                if (!file.exists()) {
                    file.mkdirs();
                }
                final String SUFFIX = ".imgtype";
                file = new File(sdcard + "/Download/" + getResources().getString(R.string.tenantid) + "_" + new Date().getTime() + SUFFIX);
                 // 关键：解析真实路径，防止符号链接绕过
                String canonicalPath = file.getCanonicalPath();
                String allowedDir = new File(sdcard, "Download").getCanonicalPath();

                if (!canonicalPath.startsWith(allowedDir)) {
                    throw new SecurityException("非法路径: " + canonicalPath);
                }
                URL url = new URL(params[0]);
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(20000);
                conn.setDoInput(true);
                conn.connect();
                Log.e("", "==dow== " + conn.getResponseCode());
                if (conn.getResponseCode() == 200) {
                    inputStream = conn.getInputStream();
                    byte[] buffer = new byte[4096];
                    int len = 0;
                    outStream = new FileOutputStream(file);
                    while ((len = inputStream.read(buffer)) != -1) {
                        outStream.write(buffer, 0, len);
                    }
                    outStream.close();
                    String path = file.getAbsolutePath();
                    FileFormatUtils.FileType fileType = FileFormatUtils.getType(path);
                    if (fileType == FileFormatUtils.FileType.GIF) {
                        path = path.replace(SUFFIX, ".gif");
                    } else if (fileType == FileFormatUtils.FileType.JPEG) {
                        path = path.replace(SUFFIX, ".jpg");
                    } else if (fileType == FileFormatUtils.FileType.PNG) {
                        path = path.replace(SUFFIX, ".png");
                    } else if (fileType == FileFormatUtils.FileType.BMP) {
                        path = path.replace(SUFFIX, ".bmp");
                    }
                    File renamedFile = new File(path);
                    file.renameTo(renamedFile);
                    result = getResources().getString(R.string.image_besaved);
                    Utility.insertIntoMediaStore(getApplicationContext(), false, renamedFile, renamedFile.lastModified());
                }else{
                    result = getResources().getString(R.string.image_save_failed);
                }
            } catch (Exception e) {

                result = getResources().getString(R.string.image_save_failed);
            } finally {
                try{
                    if(outStream != null){
                        outStream.flush();
                        outStream.close();
                    }
                    if(inputStream != null){
                        inputStream.close();
                    }
                }catch (IOException e){
                    e.printStackTrace();
                }

                if(conn != null){
                    conn.disconnect();
                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            if (isFinishing() || isDestroyed()) {
                return;
            }
            FunKt.toastCenter(WikiPhotoDetailActivity.this, result, false);

        }

    }


    @Override
    public boolean getBarTextColorIsDefault() {
        return false;
    }


}